/**
 * Created by fafan on 2018/1/17.
 * 头像裁剪
 */
'use strict';
function SweetCut($obj){
    this.$portraitAdd = $obj.$portraitAdd; //上传盒子打开按钮
    this.$avatar = $obj.$img;//页面头像回显
    this.$logoSrc = $obj.$logoSrc;//成功后头像地址 页面 隐藏域
    this.$action = $obj.$action; //提交接口地址

    this.$catBox = $('#catBox'); //外围
    this.$cutData = this.$catBox.find('#cutData')//裁剪信息
    this.$alert = this.$catBox.find('.avater-alert')//抛错信息
    this.$form = this.$catBox.find('form')//form
    this.$fileInp = this.$catBox.find('#catFileInput')//文件input
    this.$CloseBtn = this.$catBox.find('#catClose')//关闭
    this.$PreImg = this.$catBox.find('.ImgPreviewBox')//图片预览
    this.$catWrapper = this.$catBox.find('.catWrapper')//裁剪区
    this.$callback = $obj.$callback;
    this.init();
}

SweetCut.prototype = {
    constructor: SweetCut,
    support: {
        fileList: !!$('<input type="file">').prop('files'),
        blobURLs: !!window.URL && URL.createObjectURL,
        formData: !!window.FormData
    },

    init: function () {
        $('.catMaskBG').height($('.catBox').outerHeight()+100)
        if (!this.support.formData) {
            this.alert('不支持,请更换浏览器或切换极速模式');
        }
        this.support.datauri = this.support.fileList && this.support.blobURLs;
        this.addListener();

        if(typeof this.$callback != "function"){
            this.$callback = function(){}
        }
    },
    addListener: function () {
        this.$portraitAdd.on('click', $.proxy(this.openBox, this));
        this.$avatar.on('click', $.proxy(this.openBox, this));
        this.$CloseBtn.on('click', $.proxy(this.closeBox, this));
        this.$fileInp.on('change', $.proxy(this.change, this));
        this.$form.on('submit', $.proxy(this.submit, this));
    },
    submit: function () {
        if (!this.$fileInp.val()) {
            return false;
        }
        if (this.support.formData) {
            this.ajaxUpload();
            return false;
        }
    },
    ajaxUpload: function () {
        var url = this.$form.attr('action'),
            data = new FormData(this.$form[0]),
            _this = this;
        $.ajax(url, {
            type: 'post',
            data: data,
            dataType: 'json',
            processData: false,
            contentType: false,
            success: function (data) {
                _this.submitDone(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                _this.alert(textStatus || errorThrown);
            }
        });
    },
    submitDone: function (data) {
        if ($.isPlainObject(data) && data.code == 200) {
            if (data.result) {
                this.url = data.result;
                if (this.support.datauri || this.uploaded) {
                    this.uploaded = false;
                    this.cropDone();
                    layer.msg(data.msg,{icon:1,time:2000});
                } else {
                    this.uploaded = true;
                    this.startCropper();
                }

                this.$fileInp.val('');
            } else if (data.msg) {
                this.alert(data.msg);
            }
        } else {
            this.alert('Failed to response');
        }
    },
    cropDone: function () {
        this.$form.get(0).reset();
        this.$avatar.attr('src', this.url);
        this.$logoSrc.val(this.url);
        this.closeBox();
        this.$callback(this.url)
    },
    openBox: function () {
        this.$catBox.fadeIn()
        this.addaction();
        this.initPreview();
        $('body').addClass('ovfHiden')
    },
    closeBox: function () {
        this.$catBox.fadeOut()
        this.alert('')
        this.$catWrapper.empty();
        $('body').removeClass('ovfHiden')
        if(this.active){
            this.$img.cropper('destroy');
            this.active = false;
        }
    },
    startCropper: function () {
        var _this = this;
        if (this.active) {
            this.$img.cropper('replace', this.url);
        } else {
            this.$img = $('<img src="' + this.url + '">');
            this.$catWrapper.empty().html(this.$img);
            this.$img.cropper({
                aspectRatio: 1/1,
                preview: this.$PreImg.selector,
                strict: true,
                autoCropArea:0.5,
                crop: function (data) {
                    var json = [
                        '{"x":' + data.x,
                        '"y":' + data.y,
                        '"height":' + data.height,
                        '"width":' + data.width,
                        '"rotate":' + data.rotate + '}'
                    ].join();

                    _this.$cutData.val(json);
                }
            });
            this.active = true;
        }
    },
    change: function () {
        var files, file;
        if (this.support.datauri) {
            files = this.$fileInp.prop('files');
            if (files.length > 0) {
                file = files[0];
                if (this.isImageFile(file)) {
                    if (this.url) {
                        URL.revokeObjectURL(this.url); // Revoke the old one
                    }
                    this.url = URL.createObjectURL(file);
                    this.startCropper();
                }
            }
        } else {
            this.alert('不支持,请更换浏览器或切换极速模式');
        }
    },
    isImageFile: function (file) {
        if (file.type) {
            if((/\/(jpg|jpeg|png)$/.test(file.type))){
                this.alert('');
                return true
            } else{
                this.alert('格式不支持',{icon:1,time:2000})
                return false
            }
        } else {
            return /\.(jpg|jpeg|png)$/.test(file);
        }
    },
    addaction:function(){
        this.$form.attr('action',this.$action)
    },
    initPreview: function () {
        this.url = this.$avatar.attr('src');
        this.$PreImg.empty().html('<img src="' + this.url + '">');
    },
    alert: function (msg) {
        this.$alert.html(msg)
    }
};